// 一. 导入express
const express = require('express')
// 二. 实例化router对象
const router = express.Router()

const { DEBUG } = require('../config/config.default')

// 导入db模块
const { getAll, getById, exec } = require('../db')
// 三. 编写路由规则

router.get('/', async (req, res) => {
  const { page, size, notice_content } = req.query
  //  分页公式
  let offset = (page - 1) * size

  // 操作数据库
  let sql = `select count(*) as total from gg_event `
  const obj = await getById(sql)
  var sql1 = `select *  from gg_event order by event_time DESC limit ${offset},${size} `
  const data = await getAll(sql1)
  res.send({
    code: 0,
    message: '获取所有路况成功',
    result: {
      total: obj.total,
      data: data,
    },
  })
})

router.get('/:event_id', async (req, res) => {
  // 一. 解析id
  let { event_id } = req.params
  // 二. 操作数据库
  let sql = `select * from gg_event where event_id = ${event_id}`
  try {
    // 三. 返回结果
    var resData = await getById(sql)
  } catch (err) {
    res.send({
      code: 100103,
      message: '查询单个路况失败',
      result: DEBUG ? err : '',
    })
  }

  if (resData) {
    res.send({
      code: 0,
      message: '获取路况成功',
      result: resData,
    })
  } else {
    res.status(404).send({
      code: 100102,
      message: 'id对应的数据不存在',
      result: '',
    })
  }
})

// 增加事件
router.post('/', async (req, res) => {
  const { user_id, event_type, event_addr, event_mark, event_describe } =
    req.body
  if (!event_type) {
    return res.send({
      code: 100104,
      message: '参数格式不对',
      result: '',
    })
  }
  // 操作数据库
  let sql = `insert into gg_event (event_type,event_mark,event_addr,event_describe,user_id) values ('${event_type}','${event_mark}','${event_addr}','${event_describe}','${user_id}')`
  let { insertId } = await exec(sql)

  sql = `select * from gg_event where event_id=${insertId}`
  const resData = await getById(sql)
  // 返回结果
  res.send({
    code: 0,
    message: '添加成功',
    result: resData,
  })
})

// 修改事件
router.put('/:id', async (req, res) => {
  // 解析参数
  let { event_id, event_status } = req.body

  // 操作数据库
  let sql = `update gg_event set event_status='${event_status}' where event_id=${event_id}`
  await exec(sql)
  res.send({
    code: 0,
    message: '更新成功',
    result: {
      event_id,
      event_status,
    },
  })
})

// 删除事件
router.delete('/:id', async (req, res) => {
  // 解析参数
  let { id } = req.params

  // 操作数据库
  let sql = `delete from gg_event where event_id=${id}`
  await exec(sql)
  res.send({
    code: 0,
    message: '删除成功',
  })
})

// 四. 导出router对象
module.exports = router
